package com.lanqiao.attendance.common;

import com.alibaba.fastjson.JSON;
import com.lanqiao.attendance.mapper.PermissionMapper;
import com.lanqiao.attendance.pojo.Permission;
import com.lanqiao.attendance.pojo.Student;
import com.lanqiao.attendance.pojo.Teacher;
import com.lanqiao.attendance.pojo.User;
import com.lanqiao.attendance.service.UserService;
import com.lanqiao.attendance.utils.JWTUtils;
import com.lanqiao.attendance.utils.StringUtils;
import com.lanqiao.attendance.vo.ErrorCode;
import com.lanqiao.attendance.vo.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;

/**
 * @program: attendance----权限拦截器。
 * 学生   role=  1
 * 教师   role = 2
 * 管理员 role = 3
 * @description
 * @author: 刘 华
 * @create: 2022-07-12 10:52
 **/

@Component
@Slf4j
public class PermissionInterceptor implements HandlerInterceptor {
     @Autowired
    private UserService userervice;

     @Autowired
     private PermissionMapper permissionMapper;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("后进权限拦截器");

//        System.out.println(request.getMethod());
//        System.out.println(StringUtils.SegmentationPath(request.getRequestURI()));

        /**
         * 1、同样只是拦截请求控制器的url。
         * 2、获取请求头带的token，这里已经通过登录拦截器。
         * 3、
         */
        if (!(handler instanceof HandlerMethod)){
            return true;
        }
        String token = request.getHeader("Authorization");
        Object o = userervice.checkToken(token);
//        这里看看这个用户是啥角色
        if(o instanceof Student){
            System.out.println(o);
       List<Permission>permissions= permissionMapper.queryPermissionByRoleId(((Student) o).getRole());
            for (Permission permission :permissions) {
                System.out.println(permission.getUrl());
            }

        }else if(o instanceof Teacher){
            System.out.println(o);
            List<Permission>permissions= permissionMapper.queryPermissionByRoleId(((Teacher) o).getRole());
            for (Permission permission :permissions) {
                System.out.println(permission.getUrl());
            }

        }



//
//        Result result = Result.fail(ErrorCode.NO_LOGIN.getCode(), "无权限访问");
//        response.setContentType("application/json;charset=utf-8");
//        response.getWriter().print(JSON.toJSONString(result));

        return false;

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("先出权限拦截器");
    }
}
